<?php


namespace app\common;

use Swoole\Websocket\Frame;
use Swoole\Server;
use Swoole\WebSocket\Server as WebsocketServer;
use think\Config;
use think\Request;
use think\swoole\contract\websocket\HandlerInterface;

class Chat implements HandlerInterface
{
    protected $host = '0.0.0.0'; //监听所有地址
    protected $port = 8090; //监听9501端口
    /** @var WebsocketServer */
    protected $server;
    /** @var Config */
    protected $config;
    protected $option = [
        'worker_num' => 4, //设置启动的Worker进程数
        'daemonize' => false, //守护进程化（上线改为true）
        'backlog' => 128, //Listen队列长度
        'dispatch_mode' => 2, //固定模式，保证同一个连接发来的数据只会被同一个worker处理

//心跳检测：每60秒遍历所有连接，强制关闭10分钟内没有向服务器发送任何数据的连接
        'heartbeat_check_interval' => 60,
        'heartbeat_idle_time' => 600
    ];

    public function __construct(Server $server, Config $config)
    {
        $this->server = $server;
        $this->config = $config;
    }

    public function onOpen($fd, Request $request)
    {
        $uid = $request->get('uid');//客户端传递的用户id
        $token = $request->get('token');//客户端传递的用户登录token

        //省略token验证逻辑......
        if (!$token) {
            $arr = array('status' => 2, 'message' => 'token已过期');
            $this->server->push($fd, json_encode($arr));
            $this->server->close($fd);
            return;
        }

        echo "用户{$uid}建立了连接,标识为{$fd}\n";
    }

    public function onMessage(Frame $frame)
    {
        $fd = $frame->fd;
        $message = $frame->data;

        //省略通过fd查询用户uid逻辑......
        $uid = 666;
        $data['uid'] = $uid;
        $data['message'] = '用户' . $uid . '发送了:' . $message;
        $data['post_time'] = date("m/d H:i", time());
        $arr = array('status' => 1, 'message' => 'success', 'data' => $data);

        //仅推送给当前连接用户
        //$server->push($fd, json_encode($arr));

        //推送给全部连接用户
        foreach ($this->server->connections as $fd) {
            $this->server->push($fd, json_encode($arr));
        }
    }

    public function onClose($fd, $reactorId)
    {
        echo "标识{$fd}关闭了连接\n";
    }

    //建立连接时回调函数
}